package com.JUC.cha08.sec03;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * CAS缺点：ABA型典型问题
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
class Book {
    private Integer id;
    private String bookName;
}


public class AtomicStampedDemo {

    public static void main(String[] args) {
        Book javaBook = new Book(1, "javaBook");
        Book MySQLBook = new Book(2, "MySQLBook");

        AtomicStampedReference<Book> atomicStampedReference = new AtomicStampedReference<>(javaBook, 1);

        System.out.println(atomicStampedReference.getReference() + "\t" + atomicStampedReference.getStamp());

        boolean b;
        b = atomicStampedReference.compareAndSet(javaBook, MySQLBook,
                atomicStampedReference.getStamp(),
                atomicStampedReference.getStamp() + 1);
        System.out.println(b +"\t" + atomicStampedReference.getReference() + "\t" + atomicStampedReference.getStamp());

        b = atomicStampedReference.compareAndSet(MySQLBook, javaBook,
                atomicStampedReference.getStamp(),
                atomicStampedReference.getStamp() + 1);
        System.out.println(b +"\t" + atomicStampedReference.getReference() + "\t" + atomicStampedReference.getStamp());
    }


}
